
import { defineStore } from 'pinia'
import { useRouterStore } from '@/store'


export const useAuthStore = defineStore('auth', {
  state: () => ({
    accessToken: null,
    userInfo: {},
  }),
  getters: {
    isAdmin() {
      return this.userInfo?.actor === "超级管理员" ? true : false
    },
    isSchoolMaster() {
      return this.userInfo?.actor === "管理员" ? true : false
    },
    isSchoolTeacher() {
      return this.userInfo?.actor === "教师" ? true : false
    },
    getSchoolName() {
      return this.userInfo?.school || "暂无学校"
    },
    getUserName() {
      return this.userInfo?.name || "暂无用户名"
    },
    getRoleName() {
      return this.userInfo?.actor || "暂无角色"
    },
    getFirstName() {
      return this.userInfo?.name.slice(0, 1)
    },
  },
  actions: {
    // 设置token
    async setToken(accessToken) {
      this.accessToken = accessToken
    },

    // 设置用户信息
    async setUserInfo(userInfo) {
      this.userInfo = userInfo
    },

    // 重置auth
    resetAuth() {
      this.$reset()
    },

    // 去登录页
    async toLogin() {
      const { router, route } = useRouterStore()
      router.replace({
        path: '/login',
        query: { redirect: route.query?.redirect != "/login" && route.fullPath },
      })
    },
    // 登录成功后跳转
    afterLogin() {
      const { router, route } = useRouterStore()
      console.log(route);
      router.replace({
        path: route.query?.redirect || '/',
      })
    },


    // 退出登录
    async logout() {
      //清除缓存
      await $cache.local.clear()
      await $cache.session.clear()
      //到登录页
      this.toLogin()
    },
  },
  persist: true,
})
